package org.com.gr.capserver.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.com.gr.capserver.model.Cap;
import org.com.gr.capserver.model.Controller;
import org.com.gr.capserver.service.PTZHandlerService;
import org.com.gr.capserver.utils.FieldU;
import org.com.gr.capserver.utils.MongoHelper;
import org.com.gr.capserver.utils.ResultUtils;
import org.com.gr.capserver.utils.hikvisionSDK.SDKBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: PTZHandlerServiceImpl
 * Description:
 *
 * @author binbin_hao
 * @date 2023/9/8 17:49
 */
@Service
@Slf4j
public class PTZHandlerServiceImpl implements PTZHandlerService {
    @Autowired
    SDKBean sdkBean;
    @Autowired
    MongoHelper mongoHelper;
    @Override
    public ResultUtils controllerstart(Controller controller) {
        try {
            Map<String,Object> param=new HashMap<>();
            param.put(FieldU.fName(Cap::getSerial),controller.getKey());
            Cap cap=mongoHelper.findOneByParam(Cap.class,"",param);
            if (cap==null){
                log.error("没有找到对应的摄像头，摄像头序列号：{}",controller.getKey());
                return ResultUtils.fail("没有找到对应的摄像头");
            }
            if (StringUtils.isEmpty(cap.getIp()) || StringUtils.isEmpty(cap.getPort())
                    || StringUtils.isEmpty(cap.getUsername())
                    || StringUtils.isEmpty(cap.getPassword())
            ){
                log.error("摄像头必登录的必要参数不能为空，序列号：{}",controller.getKey());
                return ResultUtils.fail("摄像头必登录的必要参数不能为空");
            }
            if (SDKBean.lUserIDMap.containsKey(controller.getKey())){
                sdkBean.controllerPanStart(controller.getKey(),Integer.valueOf(controller.getCommand()),0);
            }else {
                //如果没有登录则需要重新登录一下
                String key= sdkBean.loginSDK(cap.getIp(),Integer.valueOf(cap.getPort()),cap.getUsername(),cap.getPassword(),controller.getKey());
                sdkBean.controllerPanStart(key,Integer.valueOf(controller.getCommand()),0);
            }
            return ResultUtils.ok();
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return ResultUtils.fail("控制异常");
        }
    }
}
